
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Data;

namespace Swaf.DataAccess
{
	/// <summary>
	/// Summary description for AdoNetDataResponse.
	/// </summary>
	public class AdoNetDataResponse : IDataResponse
	{
		protected AdoNetDataRequestInfo m_req;
		protected string m_defaultFormatter;
		protected object formattedResults;
		protected string m_mergeListName;

		public AdoNetDataResponse(AdoNetDataRequestInfo req, string defaultFormatter)
		{
			m_req = req;
			m_defaultFormatter = defaultFormatter;
		}

        internal AdoNetDataRequestInfo RequestInfo { get { return m_req; } }
		public virtual IDataReader Reader {get{return m_req.DataReader;}}
		public object getPassedItem(string key)
		{
			return m_req.getPassedItem(key);
		}
		public void putPassedItem(string key, object val)
		{
			m_req.putPassedItem(key,val);
		}

		internal string MergeListName { get { return m_mergeListName; } }
		#region IDataResponse Members

		public virtual object formatResults(IDataFormatter format)
		{
			m_req.DbConnection.release();
			// TODO:  Add AdoNetDataResponse.formatResults implementation
			return null;
		}

		public virtual object formatResults()
		{
			object x = null;
			DateTime startTime=DateTime.Now;

			try
			{
				if(m_defaultFormatter != null && m_defaultFormatter.Length > 0)
				{
					IDataFormatter f = getFormatter(m_defaultFormatter);
					if(f == null)
					{
						m_req.DbConnection.release();
						throw new DataResponseFormatException(m_defaultFormatter);
					}

					long startTick = Environment.TickCount;
					x = f.format();
					if (f is AdoNetBizObjFormatter)
						m_mergeListName = ((AdoNetBizObjFormatter)f).MergeListName;

					long ticks = Environment.TickCount - startTick;

					if (ticks >= (int) Application.currentApp.appData.get("LongRunningQueryThreshold-Log"))
					{
						int len = m_req.DbCommand.CommandText.Length;
						Application.currentApp.Log.println("Formatting for Data Access Request {0} on thread {1} took {2} milliseconds to execute.", m_req.DbCommand.CommandText.Substring(0, (len < 64)?len:64) + "...", AppDomain.GetCurrentThreadId(), ticks);
					}
				}
			}
			catch(Exception e)
			{
				Cmn.PerfMon.incrementCounter("DataAccessFormatExceptions");
				throw new DataAccessException(string.Format("Exception formatting results for the {0} formatter.", m_defaultFormatter), e);
			}
			finally
			{
				m_req.DataReader.Close();
				populateOutParams();
				m_req.DbConnection.release();
			}
			Cmn.PerfMon.incrementCounter("AverageTimeToFormatData", DateTime.Now.Ticks - startTime.Ticks);
			return x;
		}

		protected IDataFormatter getFormatter(string formatter)
		{
			return Application.currentApp.factories["AdoNetFormatters"].createFromPattern(m_defaultFormatter, this) as IDataFormatter;
		}

		private void populateOutParams()
		{
			IDbCommand cmd = m_req.DbCommand;
			
			foreach(Param p in m_req.SqlParams)
				if(p.direction==ParameterDirection.Output || p.direction == ParameterDirection.InputOutput)
				{
					try
					{
						if (m_req.ADONetHelper.allowParamOutputMapping(cmd.Parameters,p.dbName))
						{ 
							m_req.putPassedItem(p.name, m_req.ADONetHelper.getParamValue(cmd.Parameters,p.dbName));
						}
					}
					catch(Exception e)
					{
						Application.currentApp.Trace.write(BaseException.ExceptionTraceLevel, "Unable to Add Out Param {0}.   was {1}.",p.name,e.ToString());
						throw new Swaf.DataAccess.DataAccessException(string.Format("Unable to get output param {0} to sql statement{1}", p.name, m_req.DbCommand.CommandText), e);
					}
				}
		}

		#endregion
	}
}
